package com.example.home.attorney.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.bumptech.glide.Glide;
import com.example.home.R;
import com.example.home.attorney.bean.HotAttorneyBean;
import com.example.home.attorney.bean.LawyerCardListBean;
import com.example.home.government.bean.ImgBean;
import com.example.home.tool.GeneralClass;
import com.example.home.tool.OKHttpTool;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.example.home.tool.StaticActi.ip;

public class ConsultDetail extends AppCompatActivity {


    private ImageView imgUrl;
    private TextView name;
    private TextView workStartAt;
    private TextView serviceTimes;
    private TextView legalExpertiseName;
    private Button btnType;
    private TextView selectResult;
    private EditText edSpeed;
    private Button btnImg;
    private EditText edIphone;
    private Button btnSub;
    private TextView favorableRate;
    private HotAttorneyBean.DataBean receivedDataBean;
    private String selectedOption;
    private String filePath;
    private String serviceImgUrl;
    private static final int PNICK_IMAGE_REQUEST = 141;
    private static final int REQUEST_PERMISSION_CODE = 1;
    private final static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consult_detail);

        Intent intent = getIntent();
        Gson gson = new Gson();
        String serializedObject = intent.getStringExtra("consull");
        receivedDataBean = gson.fromJson(serializedObject, HotAttorneyBean.DataBean.class);
        initView();

        getAttorneyData();
    }

    private void getAttorneyData() {
        Glide.with(ConsultDetail.this).load(ip+receivedDataBean.getAvatarUrl()).into(imgUrl);
        name.setText(receivedDataBean.getName());
        workStartAt.setText("工作年限："+receivedDataBean.getWorkStartAt());
        serviceTimes.setText("咨询人数："+receivedDataBean.getServiceTimes());
        legalExpertiseName.setText("法律专长："+receivedDataBean.getLegalExpertiseName());
        favorableRate.setText("好评率："+receivedDataBean.getFavorableRate()+"%");
    }

    private void getTypeData() {
        OKHttpTool.doNetRequest("prod-api/api/lawyer-consultation/legal-expertise/list",
                OKHttpTool.GET,
                LawyerCardListBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        LawyerCardListBean lawyerCardListBean = (LawyerCardListBean) obj;
                        List<String> optionsList = new ArrayList<>();
                        for (LawyerCardListBean.RowsBean data : lawyerCardListBean.getRows()) {
                            optionsList.add(data.getName());
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // Show a dialog with the optionsList
                                showOptionDialog(ConsultDetail.this, "Select Legal Expertise", optionsList);
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {
                        // Handle failure
                    }
                });
    }
    private void showOptionDialog(Context context, String title, List<String> optionsList) {
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, optionsList);

        new AlertDialog.Builder(context)
                .setTitle(title)
                .setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        selectedOption = optionsList.get(which);
                        selectResult.setText(selectedOption);
                    }
                })
                .create()
                .show();
    }


    private void initView() {

        imgUrl = findViewById(R.id.imgUrl);
        name = findViewById(R.id.name);
        workStartAt = findViewById(R.id.workStartAt);
        serviceTimes = findViewById(R.id.serviceTimes);
        legalExpertiseName = findViewById(R.id.legalExpertiseName);
        favorableRate = findViewById(R.id.favorableRate);
        btnType = findViewById(R.id.btn_type);
        selectResult = findViewById(R.id.select_result);
        edSpeed = findViewById(R.id.ed_speed);
        btnImg = findViewById(R.id.btn_img);
        edIphone = findViewById(R.id.ed_iphone);
        btnSub = findViewById(R.id.btn_sub);

        btnType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getTypeData();
            }
        });

        btnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery(v);
                verifyStoragePermissions(this);
            }
        });

        btnSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SubAppeal();
            }
        });

    }

    private void SubAppeal() {
        Integer lawyerId = receivedDataBean.getId();
        Integer legalExpertiseId = receivedDataBean.getLegalExpertiseId();
        String content = edSpeed.getText().toString();
        String phone = edIphone.getText().toString();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("lawyerId", lawyerId);
            jsonObject.put("legalExpertiseId", legalExpertiseId);
            jsonObject.put("content", content);
            jsonObject.put("imageUrls", serviceImgUrl);
            jsonObject.put("phone",phone);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(content)){
            OKHttpTool.doNetRequest("prod-api/api/lawyer-consultation/legal-advice",
                    OKHttpTool.POST,
                    GeneralClass.class,
                    new OKHttpTool.NetCallback() {
                        @Override
                        public void onSuccess(Object obj) {
                            runOnUiThread(new Runnable() {
                                GeneralClass generalClass = (GeneralClass) obj;
                                @Override
                                public void run() {
                                    if (generalClass.getCode() == 200) {
                                        Toast.makeText(ConsultDetail.this, "提交成功", Toast.LENGTH_SHORT).show();
                                        ConsultDetail.this.finish();
                                    } else if (generalClass.getCode() == 500) {
                                        Toast.makeText(ConsultDetail.this, "提交失败", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }

                        @Override
                        public void onFailure(String msg) {
                            Log.e("xhf", "网络访问失败");
                        }
                    }, jsonObject.toString());
        } else {
            Toast.makeText(ConsultDetail.this, "内容不能为空", Toast.LENGTH_SHORT).show();
        }


    }

    private void verifyStoragePermissions(View.OnClickListener onClickListener) {
        try {
            //判断当前系统是否是Android6.0(对应API 23)以及以上，如果是则判断是否含有了权限
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                /***
                 * checkSelfPermission返回两个值
                 * 有权限: PackageManager.PERMISSION_GRANTED
                 * 无权限: PackageManager.PERMISSION_DENIED
                 */
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //回调函数，申请权限后回调onRequestPermissionResult函数，第一个参数为请求码，第二个参数是刚刚请求的权限集，第三个参数是请求结果，0表示授权成功，-1表示授权失败
    //requestCode：这个对应请求状态码，permissions：这个是前面你要申请的权限集合，grantResults：这个是申请权限的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                //grantResults[i]：返回0，表示授权成功，返回-1，表示授权失败
                Log.i("111333", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }

    public void openGallery(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PNICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PNICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            String imagePath = getRealPathFromUri(selectedImageUri);

            if (imagePath != null) {
                ImageView imageView = findViewById(R.id.imageView);
                imageView.setImageURI(selectedImageUri);
                btnImg.setVisibility(View.GONE);
                // 调用上传图片方法
                uploadImage(selectedImageUri);
            } else {
                // 处理无法获取文件路径的情况
                Toast.makeText(ConsultDetail.this, "上传图片失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    public String getRealPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(column_index);
                cursor.close();
                return filePath;
            } else {
                cursor.close();
            }
        }
        return null;
    }



    public void uploadImage(Uri imageUri) {
        String filePath = getRealPathFromUri(imageUri);
        File fileToUpload = new File(filePath);
        OKHttpTool.uploadFile(fileToUpload, ImgBean.class, new OKHttpTool.NetCallback() {
            @Override
            public void onSuccess(Object obj) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 上传成功后的处理逻辑
                        // obj 是服务器响应的解析结果，根据您的需求进行处理
                        serviceImgUrl = ((ImgBean) obj).getUrl();
                        Toast.makeText(ConsultDetail.this,"上传成功",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onFailure(String msg) {
                // 上传失败后的处理逻辑
                // msg 包含了失败的原因，根据您的需求进行处理
                Log.e("xhf","=="+msg);
            }
        });
    }


}